package com.ship.dispatch.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.BaseController;
import com.ship.common.core.base.Page;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.*;
import com.ship.dispatch.bo.*;
import com.ship.dispatch.model.SpYearlyPlanModel;
import com.ship.dispatch.model.dto.SchemeChartSaveDto;
import com.ship.dispatch.model.dto.SchemeChartSimpleDto;
import com.ship.dispatch.service.*;
import com.ship.dispatch.util.NumberFormatUtil;
import com.ship.dispatch.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

import static com.ship.dispatch.util.NumberFormatUtil.decimalFormat;

/**
 * 年度计划 前端控制器
 *
 * @author AbyssRabbit@163.com
 * @since 2023-10-17
 */
@RestController
@RequestMapping("/spYearlyPlan/")
@Api(value = "disSpYearlyPlan", tags = "年度计划前端控制器")
public class SpYearlyPlanController extends BaseController {

    @Autowired
    private SpYearlyPlanService spYearlyPlanService;

    @Autowired
    private SpYearPlanSchemeDetailService detailService;

    @Autowired
    private SpYearPlanSchemeService spYearPlanSchemeService;

    @Autowired
    private SpDispatchSchemeDetailService spDispatchSchemeDetailService;

    @Autowired
    private SpYearPlanSchemeDetailExService spYearPlanSchemeDetailExService;

    @Autowired
    private ExportService exportService;

    /**
     * 年度计划方案新增
     *
     * @param spYearlyPlanModel
     * @return
     */
    @PostMapping("scheme/add")
    @Log(title = "年度计划方案新增",businessType = BusinessType.INSERT)
    public JsonResult schemeAdd(@RequestBody SpYearlyPlanModel spYearlyPlanModel) {
        return spYearlyPlanService.schemeAdd(spYearlyPlanModel);
    }

    /**
     * 甘特图拖拽保存
     *
     * @return
     */
    @ApiOperation(value = "甘特图拖拽保存")
    @PostMapping("getPlanScheme/chart/save")
    @Log(title = "甘特图拖拽保存",businessType = BusinessType.INSERT)
    public JsonResult schemeChartSave(@RequestBody @Validated SchemeChartSaveDto dto) {
        dto.setCreateBy(SecurityUtils.getUsername());
        return spYearlyPlanService.schemeChartSave(dto);
    }

    /**
     * 甘特图拖动关联信息计算保存
     *
     * @return
     */
    @ApiOperation(value = "甘特图拖动关联信息计算保存")
    @PostMapping("getPlanScheme/chart/calculate/save")
    @Log(title = "甘特图拖动关联信息计算保存",businessType = BusinessType.INSERT)
    public JsonResult schemeChartCalculateSave(@RequestBody @Validated SchemeChartSaveDto dto) {
        dto.setCreateBy(SecurityUtils.getUsername());
        return spYearlyPlanService.schemeChartCalculateSave(dto);
    }

    /**
     * 修改
     *
     * @param detail
     * @return
     */
    @PostMapping("update")
    @Log(title = "修改年度计划",businessType = BusinessType.UPDATE)
    public JsonResult update(@RequestBody SpYearPlanSchemeDetailBO detail) {
        SpYearPlanSchemeDetailBO spYearPlanSchemeDetail = spYearlyPlanService.updateSpYearPlanSchemeDetail(detail);
        return JsonResult.success(spYearPlanSchemeDetail);
    }

    /**
     * 贸易利润率参数更改
     *
     * @param detail
     * @return
     */
    @ApiOperation(value = "贸易利润率参数更改")
    @PostMapping("tradingProfit/update")
    @Log(title = "修改年度计划",businessType = BusinessType.UPDATE)
    public JsonResult<SpYearPlanSchemeDetail> tradingProfitUpdate(@RequestBody SpYearPlanSchemeDetail detail) {
        return spYearlyPlanService.tradingProfitUpdate(detail);
    }

    /**
     * 获取年度计划方案调度历史
     *
     * @return
     */
    @ApiOperation(value = "获取年度计划方案调度历史")
    @PostMapping("scheme/history")
    public JsonResult<List<SpYearPlanSchemeDetail>> getSchemeHistory(@RequestBody HistoryDispatchBO historyDispatchBO) {
        return spYearlyPlanService.getSchemeHistory(historyDispatchBO);
    }

    /**
     * 删除某一条甘特图信息
     *
     * @param detailId
     * @return
     */
    @DeleteMapping("deleteSpYearPlanSchemeDetail")
    @Log(title = "删除某一条甘特图信息",businessType = BusinessType.DELETE)
    public JsonResult deleteSpYearPlanSchemeDetail(@RequestParam(value = "detailId") Long detailId) {
        detailService.deleteSpYearPlanSchemeDetail(detailId);
        return JsonResult.success();
    }

    /**
     * 查询资源合同
     *
     * @return
     */
    @GetMapping("selectAllContractNumbers")
    public JsonResult<List<ConResourceMemorandum>> selectAllContractNumbers(@RequestParam(value = "tradeModel") Integer tradeModel) {
        List<ConResourceMemorandum> models = spYearlyPlanService.selectAllContractNumbers(tradeModel);
        return JsonResult.success(models);
    }

    /**
     * 查询资源方
     *
     * @return
     */
    @PostMapping("selectAllSellers")
    public JsonResult<List<ConResourceSellerVO>> selectAllSellers(@RequestBody @Validated DispatchSellerBo sellerBo) {
        List<ConResourceSellerVO> models = new LinkedList<>();
        if(sellerBo.getSchemeType().intValue() == 1){
            if(sellerBo.getSchemeId() == null){
                return JsonResult.success(models);
            }
            models = spYearlyPlanService.selectAllSellersByScheme(sellerBo);
        }else{
            models = spDispatchSchemeDetailService.selectAllSellersByScheme();
        }
        return JsonResult.success(models);
    }

    /**
     * 根据合同编号查出资源方（卖方）
     *
     * @return
     */
    @GetMapping("selectContractNumberBySeller")
    public String getContractNumberBySeller(@RequestParam(value = "contractNumber") String contractNumber) {
        return spYearlyPlanService.getContractNumberBySeller(contractNumber);
    }

    @PostMapping("/exportYearlyPlan")
    public JsonResult<Object> exportYearlyPlan(@RequestBody SpYearlyPlan spYearlyPlan) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(CollectionUtil.isNotEmpty(spYearlyPlan.getIds())){
            queryWrapper.in("id",spYearlyPlan.getIds());
        }
        List<SpYearlyPlan> exportList = spYearlyPlanService.pageExportList(spYearlyPlan, queryWrapper, new LinkedList<>());
        for (SpYearlyPlan yearlyPlan : exportList) {
            if (1 == yearlyPlan.getState()) {
                yearlyPlan.setStatus("草稿");
            }
            if (3 == yearlyPlan.getState()){
                yearlyPlan.setStatus("下发");
            }
            if(yearlyPlan.getPlannedLoadingCapacity() == null){
                continue;
            }
            yearlyPlan.setPlannedLoadingCapacityString(NumberFormatUtil.numericFormatting(yearlyPlan.getPlannedLoadingCapacity()));
        }

        Field[] fields = SpYearlyPlan.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_yearly_plan", SecurityUtils.getUserId()), "年度计划信息");
        return JsonResult.success(url);
    }

    @PostMapping("/exportYearlyPlanDetail")
    public JsonResult<Object> exportYearlyPlanDetail(@RequestBody SpYearPlanSchemeDetail spYearPlanSchemeDetail) {
        if(spYearPlanSchemeDetail.getPlanId() == null){
            return JsonResult.failed("年度计划不存在");
        }
        //获取最新的一条被年度计划方案信息
        SpYearPlanScheme spYearPlanScheme = spYearPlanSchemeService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpYearPlanScheme>()
                        .eq(spYearPlanSchemeDetail.getPlanId() != null,SpYearPlanScheme::getPlanId,spYearPlanSchemeDetail.getPlanId())
                        .eq(SpYearPlanScheme::getIsHistory,0)
                        .and(qw -> {
                            qw.eq(SpYearPlanScheme::getCreateBy,SecurityUtils.getUsername());
                            qw.or().eq(SpYearPlanScheme::getIsShare,1);
                        })
                        .orderByDesc(SpYearPlanScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spYearPlanScheme == null){
            return JsonResult.failed("方案信息异常");
        }
        spYearPlanSchemeDetail.setSchemeId(spYearPlanScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(spYearPlanSchemeDetail.getIds() != null && spYearPlanSchemeDetail.getIds().size() > 0){
            queryWrapper.in("id",spYearPlanSchemeDetail.getIds());
        }
        queryWrapper.orderByAsc("scheme_number");
        List<SpYearPlanSchemeDetail> exportList = detailService.pageExportList(spYearPlanSchemeDetail, queryWrapper, new LinkedList<>());
        for (SpYearPlanSchemeDetail detail : exportList) {

            if (detail.getStorageCapacity()!=null){
                String result = null;
                result = decimalFormat.format(detail.getStorageCapacity());
                result = result+" m³";
                detail.setStorageCapacityString(result);
            }

            if (null != detail.getTradeType()){
                if (1 == detail.getTradeType()){
                    detail.setTradeTypeStr("长协");
                }
                if (2 == detail.getTradeType()){
                    detail.setTradeTypeStr("中期");
                }
                if (3 == detail.getTradeType()){
                    detail.setTradeTypeStr("现货");
                }
            }

            if (null != detail.getTradeBody()){
                detail.setTradeBodyStr("国贸");
            }
            if (null != detail.getTradeBody()){
                detail.setTradeBodyStr("新贸");
            }

            if(detail.getLoadingCapacity() != null){
                detail.setLoadingCapacityString(NumberFormatUtil.numericFormatting(detail.getLoadingCapacity())+" m³");
            }
            if(detail.getSingleGoodsQuantity() != null){
                detail.setSingleGoodsQuantityString(NumberFormatUtil.numericFormatting(detail.getSingleGoodsQuantity())+" MMBtu");
            }
            if(detail.getOilConsumption() != null){
                detail.setOilConsumptionString(NumberFormatUtil.numericFormatting(detail.getOilConsumption()));
            }
        }
        Field[] fields = SpYearPlanSchemeDetail.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_year_plan_scheme_detail",SecurityUtils.getUserId()), "年度计划方案详情信息");
        return JsonResult.success(url);
    }

    @PostMapping("/exportYearlyPlanDetailAndGante")
    public JsonResult<Object> exportYearlyPlanDetailAndGante(@RequestBody SpYearPlanSchemeDetail spYearPlanSchemeDetail) {
        if(spYearPlanSchemeDetail.getPlanId() == null){
            return JsonResult.failed("年度计划不存在");
        }
        //获取最新的一条被年度计划方案信息
        SpYearPlanScheme spYearPlanScheme = spYearPlanSchemeService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpYearPlanScheme>()
                        .eq(spYearPlanSchemeDetail.getPlanId() != null,SpYearPlanScheme::getPlanId,spYearPlanSchemeDetail.getPlanId())
                        .eq(SpYearPlanScheme::getIsHistory,0)
                        .and(qw -> {
//                    qw.eq(SpYearPlanScheme::getCreateBy,SecurityUtils.getStringUserId());
                            qw.eq(SpYearPlanScheme::getCreateBy,1);
                            qw.or().eq(SpYearPlanScheme::getIsShare,1);
                        })
                        .orderByDesc(SpYearPlanScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spYearPlanScheme == null){
            return JsonResult.success(new Page<>());
        }
        spYearPlanSchemeDetail.setSchemeId(spYearPlanScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(spYearPlanSchemeDetail.getIds() != null && spYearPlanSchemeDetail.getIds().size() > 0){
            queryWrapper.in("id",spYearPlanSchemeDetail.getIds());
        }
        queryWrapper.orderByAsc("scheme_number");
        List<SpYearPlanSchemeDetail> exportList = detailService.pageExportList(spYearPlanSchemeDetail, queryWrapper, new LinkedList<>());
        for (SpYearPlanSchemeDetail detail : exportList) {
            if(detail.getLoadingCapacity() != null){
                detail.setLoadingCapacityString(NumberFormatUtil.numericFormatting(detail.getLoadingCapacity())+" m³");
            }
            if(detail.getSingleGoodsQuantity() != null){
                detail.setSingleGoodsQuantityString(NumberFormatUtil.numericFormatting(detail.getSingleGoodsQuantity())+" MMBtu");
            }
            if(detail.getOilConsumption() != null){
                detail.setOilConsumptionString(NumberFormatUtil.numericFormatting(detail.getOilConsumption()));
            }
        }
        Field[] fields = SpYearPlanSchemeDetail.class.getDeclaredFields();
        String url = exportService.pageExport(exportList,fields,exportService.listStrByModuleAndUser
                ("sp_year_plan_scheme_detail",SecurityUtils.getUserId()), "年度计划方案详情信息");
        Integer size = exportList.size();
        String finalUrl = spYearPlanSchemeDetailExService.exportYearlyPlanDetailAndGante(spYearPlanSchemeDetail,url,size);
       return JsonResult.success(finalUrl);
    }

    /**
     * 甘特图下方资源列表
     * @param spYearPlanSchemeDetail
     * @return
     */
    @PostMapping("/ganttPage")
    public JsonResult<Object> page(@RequestBody SpYearPlanSchemeDetail spYearPlanSchemeDetail) {
        if(spYearPlanSchemeDetail.getPlanId() == null){
            return JsonResult.success(new Page<>());
        }
        //获取最新的一条被年度计划方案信息
        SpYearPlanScheme spYearPlanScheme = spYearPlanSchemeService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<SpYearPlanScheme>()
                        .eq(spYearPlanSchemeDetail.getPlanId() != null,SpYearPlanScheme::getPlanId,spYearPlanSchemeDetail.getPlanId())
                        .eq(SpYearPlanScheme::getIsHistory,0)
                        .and(qw -> {
                            qw.eq(SpYearPlanScheme::getCreateBy,SecurityUtils.getUsername());
                            qw.or().eq(SpYearPlanScheme::getIsShare,1);
                        })
                        .orderByDesc(SpYearPlanScheme::getCreateDate)
                        .last("limit 1")
        );
        if(spYearPlanScheme == null){
            return JsonResult.success(new Page<>());
        }
        spYearPlanSchemeDetail.setSchemeId(spYearPlanScheme.getId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("scheme_number");
        Page<SpYearPlanSchemeDetail> resultPage = detailService.page(spYearPlanSchemeDetail,queryWrapper);
        for (SpYearPlanSchemeDetail detail : resultPage.getList()) {
            if(detail.getLoadingCapacity() != null){
                detail.setLoadingCapacityString(NumberFormatUtil.numericFormatting(detail.getLoadingCapacity())+" m³");
            }
            if(detail.getSingleGoodsQuantity() != null){
                detail.setSingleGoodsQuantityString(NumberFormatUtil.numericFormatting(detail.getSingleGoodsQuantity())+" MMBtu");
            }
            if(detail.getOilConsumption() != null){
                detail.setOilConsumptionString(NumberFormatUtil.numericFormatting(detail.getOilConsumption()));
            }
            if(detail.getExpectedLoadingPortId() != null){
                List<String> portIds = new LinkedList<>();
                portIds.add(String.valueOf(detail.getExpectedLoadingPortId()));
                detail.setExpectedLoadingPorts(portIds);
            }
            if(detail.getExpectedUnloadingPortId() != null){
                List<String> portIds = new LinkedList<>();
                portIds.add(String.valueOf(detail.getExpectedUnloadingPortId()));
                detail.setExpectedUnloadingPorts(portIds);
            }
        }
        return JsonResult.success(resultPage);
    }

    /**
     * 年度计划分页列表
     * @param spYearlyPlan
     * @return
     */
    @PostMapping("/yearPlanPage")
    public JsonResult<Object> page(@RequestBody SpYearlyPlan spYearlyPlan) throws UnsupportedEncodingException {
        Page<SpYearlyPlan> resultPage = spYearlyPlanService.page(spYearlyPlan,new QueryWrapper<>());
        for (SpYearlyPlan yearlyPlan : resultPage.getList()) {
            if (1 == yearlyPlan.getState()){
                yearlyPlan.setStatus("草稿");
            }
            if (3 == yearlyPlan.getState()){
                yearlyPlan.setStatus("下发");
            }
            if(yearlyPlan.getPlannedLoadingCapacity() == null){
                continue;
            }
            yearlyPlan.setPlannedLoadingCapacityString(NumberFormatUtil.numericFormatting(yearlyPlan.getPlannedLoadingCapacity()));

        }
        return JsonResult.success(resultPage);
    }

    @GetMapping("/getPlanYearById/{serviceId}")
    public JsonResult<Object> getPlanYearById(@PathVariable("serviceId") Long serviceId) throws UnsupportedEncodingException {
        SpYearPlanScheme spYearPlanScheme = spYearPlanSchemeService.getById(serviceId);
        SpYearlyPlan resultPage = null;
        if(spYearPlanScheme!=null){
            resultPage = spYearlyPlanService.getById(spYearPlanScheme.getPlanId());
        }
        return JsonResult.success(resultPage);
    }
    /**
     * 甘特图下方资源详情
     * @param schemeId
     * @return
     */
    @GetMapping("/selectGanttInfo")
    public JsonResult selectGanttInfo(@RequestParam(value = "schemeId") Long schemeId) {
        SpYearPlanSchemeDetail schemeDetail = detailService.getBaseMapper().selectById(schemeId);
        return JsonResult.success(schemeDetail);
    }

    /**
     * 获取年度计划方案甘特图信息
     *
     * @return
     */
    @ApiOperation(value = "获取年度计划方案甘特图信息")
    @PostMapping("getPlanScheme/chart")
    public JsonResult<SpYearPlanSchemeDetail> getPlanSchemeChart(@RequestBody SchemeChartSimpleDto dto) {
        return spYearlyPlanService.getPlanSchemeChart(dto);
    }

    /**
     * 修改年度计划计划装载量信息
     *
     * @return
     */
    @ApiOperation(value = "修改年度计划计划装载量信息")
    @PostMapping("capacity/update")
    @Log(title = "修改年度计划计划装载量信息",businessType = BusinessType.UPDATE)
    public JsonResult capacityUpdate(@RequestBody SpYearPlanCapacityRecord dto) {
        return spDispatchSchemeDetailService.capacityUpdate(dto);
    }





    /**
     * 年度计划方案还原
     *
     * @return
     */
    @ApiOperation(value = "年度计划方案还原")
    @GetMapping("scheme/rollback/{schemeId}")
    public JsonResult schemeRollback(@PathVariable(value = "schemeId") String schemeId) {
        return spDispatchSchemeDetailService.schemeRollback(schemeId);
    }

    /**
     * 根据方案详情ID获取变更历史记录
     *
     * @return
     */
    @ApiOperation(value = "根据方案详情ID获取变更历史记录")
    @PostMapping("scheme/detail/history")
    public JsonResult<List<SpYearPlanSchemeDetail>> getSchemeDetailHistory(@RequestBody @Validated SchemeChartSimpleDto dto) {
        return spDispatchSchemeDetailService.getSchemeDetailHistory(dto);
    }

}
